import React from 'react'
import {connect} from 'react-redux'
const axios = require('axios')
const ipcRenderer = require('electron').ipcRenderer
import SweetAlert from 'react-bootstrap-sweetalert'
import withStyles from '@material-ui/core/styles/withStyles'
import sweetAlertStyle from '../../asset/jss/material-dashboard-pro-react/views/sweetAlertStyle.jsx'
import TextField from '@material-ui/core/TextField'
import InputAdornment from '@material-ui/core/InputAdornment'
import Button from '@material-ui/core/Button'
import Search from '@material-ui/icons/Search'
import Grid from '@material-ui/core/Grid'
import {testid} from './function'
const authOpt = require('./pack').authOpt
const SERVERURL = require('./constent').SERVERURL
const initState = {
    alert: null,
    alertMsg: ''
}
let preStu = {}
class HomePage extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            ...initState,
            search: '',
        }
    }
    componentDidMount(){
        const handleThis = this
        ipcRenderer.on('updateReady', function (event, text) {
            if (preStu.cardid === text.cardid && (Date.parse(new Date()) - preStu.t <= 5000)) {
                return handleThis.returnState(false)
            }
            preStu.cardid = text.cardid
            preStu.t = Date.parse(new Date())
            const url = SERVERURL + 'api/isheorshenmystudent/'
            const authoptions = authOpt({url, data: text,})
            axios(authoptions).then((response) => {
                const r = response.data
                if (r.length === 0) {
                    handleThis.returnState(false)
                    handleThis.autoCloseAlert(` ${text.name.split('').filter(a => a !== ' ').join('')} 非本校学员`)
                } else {
                    const stu = r.pop()
                    handleThis.htmlAlert(stu.name, '是本校学员', stu.numberid)
                }
            }).catch(() => {
                handleThis.returnState(false)
            })
        })
        this.handleCarTcp()
    }
    handleCarTcp = () => {
        const handleThis = this
        ipcRenderer.on('carHeartBeat', function (event, text) {
            const licensePlate = text.split(':').pop()
            if (licensePlate === '无牌车')return handleThis.returnIsCarOpen(false)
            const url = SERVERURL + 'api/isourcar/'
            const authoptions = authOpt({url, data: {licensePlate},})
            axios(authoptions).then((response) => {
                const r = response.data
                if (r.length === 0) {
                    handleThis.returnIsCarOpen(false)
                    handleThis.autoCloseAlert(` ${licensePlate} 非本校车辆,禁止进入`)
                } else {
                    handleThis.carAlert(` ${licensePlate} 是本校车辆`)
                }
            }).catch(() => {handleThis.returnState(false)})

        })
    }
    returnIsCarOpen(open){
        ipcRenderer.sendSync( 'isOpenTheCarDoor', open ? '1\n' : '0\n' )
    }
    returnState(open){
        ipcRenderer.sendSync(
            'quitAndInstall', open
                ? '1\n'
                : '0\n'
        )
    }
    hideAlert (){
        this.setState({
            ...initState
        })}
    successGoin (){
        this.returnState(true)
        this.hideAlert()
    }
    denyGoin (){
        this.returnState(false)
        this.hideAlert()
    }
    cancelDetele(alertMsg) {
        this.setState({alert: (
            <SweetAlert danger='danger' style={{
                display: 'block',
                marginTop: '-100px',
            }} title={alertMsg} onConfirm={() => this.hideAlert()} onCancel={() => this.hideAlert()}>
            </SweetAlert>)}
        )
    }
    componentWillUnmount(){
        ipcRenderer.removeAllListeners('updateReady')
        ipcRenderer.removeAllListeners('carHeartBeat')
    }
    autoCloseAlert(alertMsg, time = 2000) {
        this.setState({alert: (
            <SweetAlert style={{
                display: 'block',
                marginTop: '-100px',
            }} title={alertMsg} onConfirm={() => this.hideAlert()} showConfirm={false}>
            </SweetAlert>)}
        )
        setTimeout(this.hideAlert.bind(this), time)
    }
    basicAlert(alertMsg) {
        this.setState({alert: (
            <SweetAlert style={{
                display: 'block',
                marginTop: '-100px',
            }} title={alertMsg} onConfirm={() => this.hideAlert()} onCancel={() => this.hideAlert()} confirmBtnCssClass={this.props.classes.button + ' ' + this.props.classes.success}/>)})
    }
    warningWithConfirmMessage(alertMsg) {
        this.setState({alert: (<SweetAlert warning='warning' style={{
            display: 'block',
            marginTop: '-100px',
        }} title={alertMsg} onConfirm={() => this.successGoin()} onCancel={() => this.denyGoin()} confirmBtnCssClass={this.props.classes.button + ' ' + this.props.classes.success}
        cancelBtnCssClass={this.props.classes.button + ' ' + this.props.classes.danger} confirmBtnText='确认放行' cancelBtnText='禁止进入' showCancel='showCancel' >
        </SweetAlert>)})
    }
    htmlAlert(name, alertMsg, numberid) {
        const src = `http://59.37.20.100:8888/jdcjsy_dg/ImgServlet?tpbh=${numberid}&ssjg=441900&pxjgbh=441900042&tplx=sqxy&date=Fri%20Jul%2013%202018%2009:41:47%20GMT+0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)`
        this.setState({alert: (<SweetAlert style={{
            display: 'block',
            marginTop: '-100px',
        }} title={''} onConfirm={() => this.successGoin()} onCancel={() => this.denyGoin()} confirmBtnText='确认放行' confirmBtnCssClass={this.props.classes.button + ' ' + this.props.classes.success}>
            <img src={src} style={{
                width: 100,
                height: 140,
            }}/>
            <br/> {name}
            <br/> {alertMsg}
        </SweetAlert>)})
    }
    carAlert(alertMsg) {
        this.setState({alert: (<SweetAlert style={{
            display: 'block',
            marginTop: '-100px',
        }} title={''} onConfirm={() => {
            this.returnIsCarOpen(true)
            this.hideAlert()
        }} onCancel={() =>{
            this.returnIsCarOpen(false)
            this.hideAlert()
        }} confirmBtnText='确认放行' confirmBtnCssClass={this.props.classes.button + ' ' + this.props.classes.success}>
            <br/> {alertMsg}
        </SweetAlert>)})
    }
    searching = ()=>{
        const {search} = this.state
        if(testid(search).status !== 1) return this.autoCloseAlert('身份证格式不正确', 1000)
        const url = SERVERURL + 'api/isheorshenmystudent/input'
        const authoptions = authOpt({url, data: {cardid: search},})
        axios(authoptions).then((response) => {
            const r = response.data
            if (r.length === 0) {
                this.autoCloseAlert(` ${search} 非本校学员`)
            } else {
                const stu = r.pop()
                this.htmlAlertInput(stu.name, '是本校学员', stu.numberid)
            }
        })
    }
    successGoinInput(){
        ipcRenderer.sendSync('openTheDoor')
        this.hideAlert()
    }
    htmlAlertInput(name, alertMsg, numberid) {
        const src = `http://59.37.20.100:8888/jdcjsy_dg/ImgServlet?tpbh=${numberid}&ssjg=441900&pxjgbh=441900042&tplx=sqxy&date=Fri%20Jul%2013%202018%2009:41:47%20GMT+0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)`
        this.setState({alert: (<SweetAlert style={{
            display: 'block',
            marginTop: '-100px',
        }} title={''} onConfirm={() => this.successGoinInput()} onCancel={() => this.hideAlert()} confirmBtnText='确认放行' confirmBtnCssClass={this.props.classes.button + ' ' + this.props.classes.success}>
            <img src={src} style={{
                width: 100,
                height: 140,
            }}/>
            <br/> {name}
            <br/> {alertMsg}
        </SweetAlert>)})
    }
    handleKeyPress = (event) => {
        if (event.key == 'Enter') this.searching()
    }
    render() {
        return (<div>
            <Grid container spacing={24} style={{marginTop: 20}}>
                <Grid item xs></Grid>
                <Grid item xs={6}>
                    <TextField
                        id="score1times"
                        label=""
                        fullWidth
                        placeholder="身份证号"
                        value={this.state.search}
                        onKeyPress={this.handleKeyPress}
                        onChange={(event)=> this.setState({search: event.target.value})}
                        InputProps={{endAdornment: (<InputAdornment position="end">
                            <Button
                                variant="fab"
                                mini
                                onClick = {this.searching}
                                style={{backgroundColor: '#2196f3', marginTop: -4, marginRight: -40 }}
                                aria-label="Add">
                                <Search style={{color: '#FFF'}} />
                            </Button>
                        </InputAdornment>)}}
                        margin="normal"/>
                </Grid>
                <Grid item xs></Grid>
            </Grid>
            {this.state.alert}
        </div>)
    }
}
function mapStateToProps() {
    return {}
}
export default connect(mapStateToProps)(withStyles(sweetAlertStyle)(HomePage))
